package edu.biwu.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

//将ConnectionFactory指定为组件,便于Spring管理
@Component //只有@Component才能被Spring管理 然后才能在里面使用@Autowired 然后再获取Connection对象等
public class ConnectionFactory {
    @Autowired
    private ThreadLocal<Connection> threadLocal;

    @Autowired
    private DataSource dataSource;

    public Connection currentThreadConnection(){
        //1.从ThreadLocal中获取当前线程的Connection
        Connection connection = threadLocal.get();

        //2.判断当前线程的Connection是否为空
        try {
            if (connection==null) {
                //3.如果为空,则从数据源中获取一个Connection
                 connection = dataSource.getConnection();
                //4.将获取到的Connection绑定到当前线程中
                threadLocal.set(connection);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
        return connection;
    }
}
